package com.example.bober.zad4;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.DocumentsContract;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;

import com.example.bober.zad3.R;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;


public class MyActivity extends Activity {

    NumberPicker numberPicker;
    NumberPicker numberPicker2;
    EditText editText;
    EditText editText2;
    int minuty;
    double dolna;
    double gorna;
    boolean click;
    Watek w;
    Button button;
    Button button2;
    static String cena;
    int id;

    protected void popraw(){
        button.setVisibility(View.INVISIBLE);
        click = false;
        button2.setText("Uruchom");
    }

    public void update(View view){
        try {
            int pom = numberPicker.getValue()*60000;
            int sek = numberPicker2.getValue()*1000;
            //minuty = numberPicker.getValue()*1000;
            Log.d("number", String.valueOf(pom));
            double pom2 = Double.parseDouble(editText.getText().toString());
            //dolna = Double.parseDouble(editText.getText().toString());
            Log.d("dolna", String.valueOf(pom2));
            double pom3 = Double.parseDouble(editText2.getText().toString());
            //gorna = Double.parseDouble(editText2.getText().toString());
            Log.d("gorna", String.valueOf(pom3));
            if(pom2 <= pom3){
                minuty = pom + sek;
                dolna = pom2;
                gorna = pom3;
            }
            else
                Toast.makeText(getApplicationContext(), "granica dolna musi byc mniejsza lub rowna gornej",
                        Toast.LENGTH_SHORT).show();
        } catch (final NumberFormatException e) {
            Toast.makeText(getApplicationContext(), "musisz podac liczbe calkowita", Toast.LENGTH_SHORT).show();
        }
    }

    public void uruchom(View view){
        try {
            minuty = numberPicker.getValue() * 60000 + numberPicker2.getValue()*1000;
            Log.d("number", String.valueOf(minuty));
            dolna = Double.parseDouble(editText.getText().toString());
            Log.d("dolna", String.valueOf(dolna));
            gorna = Double.parseDouble(editText2.getText().toString());
            Log.d("gorna", String.valueOf(gorna));

            if (click == false & dolna <= gorna) {
                w = new Watek();
                //p = new Pijnuj();
                w.execute();
                //p.execute();
                click = true;
                button.setVisibility(View.VISIBLE);
                button2.setText("Kill");
            } else if (click == true) {
                w.trwaj = false;
                click = false;
                button.setVisibility(View.INVISIBLE);
                button2.setText("Uruchom");
            }
            else
                Toast.makeText(getApplicationContext(), "granica dolna musi byc mniejsza lub rowna gornej",
                        Toast.LENGTH_SHORT).show();
        }
         catch (final NumberFormatException e) {
                Toast.makeText(getApplicationContext(), "musisz podac liczbe calkowita", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        id = 0;
        button2 = (Button) findViewById(R.id.ur);
        button = (Button) findViewById(R.id.zmien);
        click = false;
        numberPicker = (NumberPicker) findViewById(R.id.piker);
        numberPicker.setMinValue(0);
        numberPicker.setMaxValue(Integer.MAX_VALUE);
        numberPicker.setWrapSelectorWheel(false);
        numberPicker.setValue(1);

        numberPicker2 = (NumberPicker) findViewById(R.id.piker2);
        numberPicker2.setMinValue(0);
        numberPicker2.setMaxValue(60);
        numberPicker2.setValue(0);

        editText = (EditText) findViewById(R.id.wartosc);
        editText2 = (EditText) findViewById(R.id.wartosc2);

    }

    public void noty(){
        NotificationManager notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        Intent toLouch = new Intent(MyActivity.this, Zmiana.class);
        PendingIntent intentBack = PendingIntent.getActivity(MyActivity.this, 0, toLouch, 0);
        /*Notification notification = new Notification.Builder(this)
                .setContentTitle("Zmiana ceny")
                .setContentText("Aktualna cena: "+cena)
                .setSmallIcon(R.drawable.not)
                .setContentIntent(intentBack)
                .setAutoCancel(true).build();*/
        Notification notification = new Notification(R.drawable.not, "Zmiana ceny", System.currentTimeMillis());
        notification.setLatestEventInfo(getApplicationContext(), "Zmiana ceny", "Aktualna cena: "+cena, intentBack);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.vibrate = new long[] {0, 200, 200, 600, 600};
        notification.flags |= Notification.FLAG_INSISTENT;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        notification.ledARGB = Color.GREEN;
        notification.ledOnMS = 1000;
        notification.ledOffMS = 1000;
        notification.audioStreamType = AudioManager.STREAM_NOTIFICATION;
        notification.sound = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.nokia_3310);
        notificationManager.notify(id, notification);
        id++;


    }

    private class Watek extends AsyncTask<Void, Void, Void>{

        boolean trwaj;
        String s;

        @Override
        protected void onPreExecute(){
            trwaj = true;
            s = "https://blockchain.info/pl/tobtc?currency=PLN&value=1000";
        }

        @Override
        protected Void doInBackground(Void... params) {


            while (trwaj){
                try {
                    Log.d("JSwa", "Connecting to [" + s + "]");
                    Document doc = Jsoup.connect(s).get();
                    Log.d("JSwa", "Connected to [" + s + "]");
                    Elements links = doc.getElementsByTag("body");
                    String t = links.text();
                    if(Double.parseDouble(t) > gorna | Double.parseDouble(t) < dolna){
                        trwaj = false;
                        cena = t;
                        noty();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                popraw();
                            }
                        });
                    }
                    else
                        Thread.sleep(minuty);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            return null;
        }
    }

}
